import { ref, defineComponent, reactive, onMounted } from 'vue'
import {
  ElButton as Button,
  ElMessage as message,
  ElMessageBox as messageBox,
} from 'element-plus'
import type { AccountData } from '@/types/views/system/account'
import { getApi } from '@/api/views/system/account'
import type { FormInstance } from 'element-plus'
import { formatDate } from '@/utils'
import searchListFun from './config/search'
import { default as columnsFunc } from './config/columns'
import formListFunc from './config/dialog'
import { useI18n } from 'vue-i18n'
export default defineComponent({
  name: 'account',
  setup() {
    const { t } = useI18n()
    // 搜索栏
    const searchParams = ref({})
    const onChangeSearch = (params: any) => {
      console.log('params', params)
      searchParams.value = params
      fetchData()
    }

    // 表格
    const tableData = ref<AccountData[] | null>(null)
    const handleSelectionChange = (val: AccountData[]) => {}
    onMounted(() => {
      fetchData()
    })
    const fetchData = async () => {
      const res: any = await getApi({
        pageIndex: pagination.currentPage,
        pageSize: pagination.pageSize,
      })
      if (res.code === 200) {
        tableData.value = res.data.list
        pagination.total = res.data.count
      }
    }

    const handeEdit = (row: any) => {
      showModal('edit', row)
    }
    const handleDel = (row: { username: any }) => {
      messageBox
        .confirm(
          `确定要删除用户名为"${row.username}"的数据项吗?`,
          t('messageBox.tips'),
          {
            icon: (
              <>
                <i class="iconfont icon-jinggao"></i>
              </>
            ),
            confirmButtonText: t('messageBox.determine'),
            cancelButtonText: t('messageBox.cancel'),
            type: 'warning',
          }
        )
        .then(() => {
          message({
            type: 'success',
            message: t('messageBox.deleteSucceeded'),
          })
        })
        .catch(() => {
          message({
            type: 'info',
            message: t('messageBox.undelete'),
          })
        })
    }

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 20,
      total: 0,
    })

    const handleCurrentChange = (currentPage: any) => {
      pagination.currentPage = currentPage
      fetchData()
    }
    const handleSizeChange = (val: number) => {
      pagination.pageSize = val
      fetchData()
    }
    // 对话框
    const handleFormInline = reactive<AccountData>({
      username: '',
      roleName: '',
      deptName: '',
      mobile: '',
      status: true,
      createdAt: '',
      updatedAt: '',
    })
    const dialogConfig = reactive({
      dialogVisible: false,
      closeOnClickModal: false,
      beforeClose: () => (dialogConfig.dialogVisible = false),
    })
    const formConfig = reactive({
      ref: 'formRef',
      formInline: handleFormInline,
    })
    const formItemConfig = reactive({
      title: t('dialog.newData'),
      formList: formListFunc(t),
    })
    const showModal = (type: string, record?: AccountData) => {
      console.log('type, record', type, record)
      dialogConfig.dialogVisible = true
      formItemConfig.title =
        type === 'add' ? t('dialog.newData') : t('dialog.editData')

      if (type == 'edit') {
        Object.keys(handleFormInline).map(
          (key) =>
            (handleFormInline[key as keyof typeof handleFormInline] =
              record && record[key as keyof typeof record])
        )
        handleFormInline.status = handleFormInline.status == '0'
        handleFormInline.createdAt = new Date(handleFormInline.createdAt)
      } else {
      }
    }
    const dialogRefreshTable = () => {}

    const handleSubmit = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          dialogConfig.dialogVisible = false
          setTimeout(() => {
            console.table(handleFormInline)
            dialogRefreshTable()
          }, 300)
        } else {
        }
      })
    }
    const handleAdd = () => {
      showModal('add')
    }
    const $slots = {
      handleExtra: () => (
        <div>
          <Button type="primary" onClick={handleAdd}>
            {t('button.newlyAdded')}
          </Button>
        </div>
      ),
    }
    return () => (
      <s-design
        v-slots={$slots}
        searchList={searchListFun()}
        onChangeSearch={onChangeSearch}
        handleSelectionChange={handleSelectionChange}
        data={tableData.value}
        columns={columnsFunc(handeEdit, handleDel, t)}
        pagination={pagination}
        handleCurrentChange={handleCurrentChange}
        handleSizeChange={handleSizeChange}
        dialogConfig={dialogConfig}
        formConfig={formConfig}
        formItemConfig={formItemConfig}
        handleSubmit={handleSubmit}
      />
    )
  },
})
